using System;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

namespace DevCangjie.Pages.EditPage
{
    public sealed partial class FindReplaceControl : UserControl
    {
        public event RoutedEventHandler CloseRequested;
        private EditPage? _editPage;

        // 公共属性用于引用 EditPage
        public EditPage ParentEditPage { get; set; }

        // 公共无参数构造函数
        public FindReplaceControl()
        {
            this.InitializeComponent();
        }

        public FindReplaceControl(EditPage editPage) : this()
        {
            _editPage = editPage;
        }

        private void FindNextButton_Click(object sender, RoutedEventArgs e)
        {
            string searchText = FindTextBox.Text;
            bool isMatchCase = MatchCaseCheckBox.IsChecked ?? true;
            ParentEditPage?.FindNext(searchText, isMatchCase);
        }

        private void ReplaceButton_Click(object sender, RoutedEventArgs e)
        {
            string searchText = FindTextBox.Text;
            string replaceText = ReplaceTextBox.Text;
            bool isMatchCase = MatchCaseCheckBox.IsChecked ?? true;
            ParentEditPage?.Replace(searchText, replaceText, isMatchCase);
        }

        private async void ReplaceAllButton_Click(object sender, RoutedEventArgs e)
        {
            string searchText = FindTextBox.Text;
            string replaceText = ReplaceTextBox.Text;
            bool isMatchCase = MatchCaseCheckBox.IsChecked ?? true;

            try
            {
                if (ParentEditPage != null)
                {
                    await ParentEditPage.ReplaceAllAsync(searchText, replaceText, isMatchCase);
                }
                else
                {
                    // 显示错误提示
                    var dialog = new ContentDialog
                    {
                        Title = "错误",
                        Content = "未能找到父级编辑页面。",
                        CloseButtonText = "确定",
                        DefaultButton = ContentDialogButton.Close,
                        XamlRoot = this.XamlRoot
                    };
                    await dialog.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                // 记录异常（可选）
                ConsolePage.ConsolePage.Instance.AppendErrorOutput($"替换操作失败: {ex.Message}");

                // 显示异常提示
                var errorDialog = new ContentDialog
                {
                    Title = "替换失败",
                    Content = $"发生错误: {ex.Message}",
                    CloseButtonText = "确定",
                    DefaultButton = ContentDialogButton.Close,
                    XamlRoot = this.XamlRoot
                };
                await errorDialog.ShowAsync();
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            CloseRequested?.Invoke(this, e);
        }
    }
}
